<template>
  <div class="centeet">
    <a-drawer :title="basicDrawerString" placement="right" :visible="basicDrawerVisible" :width="600" @close="onClose">
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="ruleForm" :model="form"
                    labelAlign="left">
        <a-form-model-item :label="$t('message.Emission_source')" prop="emissionSourceName">
          <a-input id="error" :placeholder="$t('message.Please_enter')" v-model="form.emissionSourceName" :disabled="formDisabled"/>
        </a-form-model-item>
        <a-form-model-item :label="$t('message.facilities_activities')" prop="type">
          <j-dict-select-tag style="width: 100%" v-model="form.activitieId" :dictCode="'cy_org_activitie,name,id,del_flag = 0'" :placeholder="$t('message.Please_select')"
                             :disabled="formDisabled"/>
        </a-form-model-item>

        <a-form-model-item :label="$t('message.Emission_type')" prop="type">
          <j-dict-select-tag style="width: 100%" v-model="form.type" :dictCode="'emission_type'" :placeholder="$t('message.Please_select')"
                             :disabled="formDisabled"/>
        </a-form-model-item>
        <a-form-model-item :label="$t('message.Active_data_unit')" prop="dataUnit">
          <a-select v-model="form.dataUnit" :disabled="formDisabled" :placeholder="$t('message.Please_select')"
                    @change="dataUnitChange">
            <a-select-opt-group :key="key" :value="key" :label="key"
                                v-for="(value, key, index) in getAllUnitByGroupData">
              <a-select-option :key="itemA.id" :value="itemA.id" v-for="(itemA,indexA) in value">
                {{ itemA.unitCode }}
              </a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label="$t('message.Carbon_emission_factor')" prop="carbonDataId">
          <div class="tianjia" v-if="!form.carbonDataId">
            <div class="color">{{$t('message.please_add_factor')}}</div>
            <div>
              <a-button @click="handleAdd" class="leftShoudong" icon="plus">{{$t('message.Manually_add')}}</a-button>
              <a-button @click="handleAdd(1)" class="leftChaxun marRight" icon="plus">{{$t('message.Select_factor')}}</a-button>
            </div>
          </div>
          <div v-else>
            <yzCard :item="selectedRows"/>
            <div class="manual">
              <div class="manualOperation" @click="handleAdd" v-if="!formDisabled">
                <img src="../../assets/carbon/img9.png" alt=""/>
                {{$t('message.Manually_add')}}
              </div>
              <div class="manualOperation" @click="handleAdd(1)" v-if="!formDisabled">
                <img src="../../assets/carbon/img10.png" alt=""/>
                {{$t('message.Add_again')}}
              </div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item :label="$t('message.Unit_proportional_conversion')" prop="ratio">
          <div></div>
          <div class="">
            1{{ province ? province.unitCode : "" }} <span class="color1">({{$t('message.Active_data_unit')}})</span>=
            <a-input id="error" v-model="form.ratio" class="inpts" :placeholder="$t('message.Please_enter')" :disabled="formDisabled"/>
            {{ selectedRows.denominatorUnit }} <span class="color1"> ({{$t('message.Factor_denominator_unit')}})</span>
          </div>
        </a-form-model-item>

        <a-form-model-item :label="$t('message.Active_data')">
          <div></div>
          <div class="">
            <a-input id="error" v-model="form.data" class="inpts" :placeholder="$t('message.Please_enter')" :disabled="formDisabled"/>
          </div>
        </a-form-model-item>

        <div class="drawerOptionBox">
          <a-button style="margin-right: 8px" @click="onClose" :disabled="formDisabled"> {{$t('message.Cancel')}}</a-button>
          <a-button type="primary" @click="onSubmit" :disabled="formDisabled"> {{$t('message.Confirm')}}</a-button>
        </div>
      </a-form-model>
    </a-drawer>
    <!--选择碳排因子弹窗-->
    <a-modal :title="$t('message.selective_carbon_emission_factor')" :visible="visible2" @ok="handleOk2" @cancel="handleCancel" :width="1524">
      <yzChooseView @onselectedRows="onselectedRows" v-if="visible2"/>
    </a-modal>
    <!--手动添加碳排因子弹窗-->
    <a-modal :title="$t('message.manually_add_carbon_emission_factors')" :visible="visible3" @ok="handleOk3" @cancel="handleCancel" :width="1000">
      <yzAddView ref="yzAddView" v-if="visible3"/>
    </a-modal>
  </div>
</template>
<script>
import {getAction, postAction, deleteAction} from "@api/manage";
import yzAddView from "@comp/common/yzAddView.vue";
import yzChooseView from "@comp/common/yzChooseView.vue";
import yzCard from "@comp/common/yzCard2.vue";

export default {
  components: {
    yzCard,
    yzChooseView,
    yzAddView,
  },
  name: "basicCheckDetailEditDrawer",
  props: {
    basicDrawerVisible: {
      type: Boolean,
      default: false,
    },
    basicDrawerString: {
      type: String,
      default() {
        return this.$t('message.New_emission_source')
      }
    },
    basicDrawerList: {
      type: Object,
      default: {},
    },
    formDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      standardIsoData:[],
      selectedRows: {},
      cachesSlectedRows: {},
      labelCol: {span: 6},
      wrapperCol: {span: 18},
      province: {
        unitCode: ''
      },
      getAllUnitByGroupData: {}, // 单位分组数据
      visible2: false,
      visible3: false,
      form: {},
      rules: {
        emissionSourceName: [{required: true, message: this.$t('message.please_fill_in_the_template_name'), trigger: "blur"}],
        source: [{required: true, message: this.$t('message.please_fill_in_the_emission_source'), trigger: "blur"}],
        type: [
          {required: true, message: this.$t('message.please_select_the_emission_type'), trigger: "blur"},
        ],
        dataUnit: [
          {required: true, message: this.$t('message.please_select_the_active_data_unit'), trigger: "blur"},
        ],
        carbonDataId: [
          {required: true, message: this.$t('message.please_select_a_carbon_emission_factor'), trigger: "blur"},
        ],
        ratio: [{required: true, message: this.$t('message.please_fill_in_the_conversion_ratio'), trigger: "blur"}],
      },
      url:{
        edit: "/orgCheckCheckDetail/edit",
      }
    };
  },
  watch: {
    basicDrawerList: {
      immediate: true,
      handler(val, nqw) {
        console.log(val, nqw);
        //拷贝对象
        this.form = JSON.parse(JSON.stringify(val));
        this.listInfo();
      },
    },
  },
  mounted() {
    this.getAllUnit();
  },
  methods: {
    onselectedRows(value) {
      console.log(value.name, 6);
      this.cachesSlectedRows = value;
    },
    handleOk3() {
      if (!this.$refs.yzAddView.checkFormData()) {
        return
      }
      console.log(this.$refs.yzAddView.queryParam);
      postAction(
          "/emission/factor/cyEmissionFactor/addEmissionByCarbonCheck",
          this.$refs.yzAddView.queryParam
      ).then((res) => {
        if (res.success) {
          this.$message.success(this.$t('message.operation_success'))
          this.form.carbonDataId = res.result
          this.listInfo();
        }
      });
    },
    /**
     * 获取因子数据
     */
    listInfo() {
      if (!this.form.carbonDataId){
        return
      }
      console.log('listInfo', this.form);
      getAction("/emission/factor/cyEmissionFactor/listInfo", {
        id: this.form.carbonDataId
      }).then((res) => {
        if (res.success) {
          this.selectedRows = {
            id: res.result.emissionFactorObject.id,
            name: res.result.emissionFactorObject.name,
            model: res.result.emissionFactorObject.model,
            factorValue: res.result.emissionFactorDataObject.factorValue,
            numeratorUnit: res.result.emissionFactorDataObject.numeratorUnit,
            denominatorUnit: res.result.emissionFactorDataObject.denominatorUnit,
            releaseOrg: res.result.emissionFactorObject.releaseOrg,
            releaseYear: res.result.emissionFactorObject.releaseYear,
          };
          this.visible3 = false;
          console.log(this.selectedRows);
        }
      });
    },
    /**
     * 活动数据单位list
     */
    getAllUnit() {
      // 单位
      getAction('/emission/factor/cyEmissionUnit/getAllUnitByGroup').then((res) => {
        if (res.success) {
          this.getAllUnitByGroupData = res.result || {}
          this.initUnitChange(this.form.dataUnit)
        }
      });
    },
    /**
     * 添加修改
     */
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let reqUrl = this.url.edit
          postAction(reqUrl, this.form).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('message.operation_success'))
              this.$emit("onCloseBasicDrawerVisible", false);
            }
          });
        } else {
          return false;
        }
      });
    },
    handleOk2() {
      this.selectedRows = this.cachesSlectedRows
      this.form.carbonDataId = this.cachesSlectedRows.id;
      this.unitChange()
      this.visible2 = false;
    },
    handleCancel() {
      this.visible2 = false;
      this.visible3 = false;
    },
    //打开抽屉
    handleAdd(value) {
      if (value == 1) {
        // 选择因子
        this.visible2 = true;
      } else {
        // 手动添加
        this.visible3 = true;
      }
    },
    //活动单位
    initUnitChange(e) {
      console.log('initUnitChange', e,this.getAllUnitByGroupData)
      for (let key in this.getAllUnitByGroupData) {
        let value = this.getAllUnitByGroupData[key]
        for (let index = 0; index < value.length; index++) {
          if (value[index].id == e) {
            this.$set(this, 'province', value[index])
          }
        }
      }
      console.log('initUnitChange', this.form)
    },
    dataUnitChange(e) {
      console.log('dataUnitChange', e,this.getAllUnitByGroupData)
      for (let key in this.getAllUnitByGroupData) {
        let value = this.getAllUnitByGroupData[key]
        for (let index = 0; index < value.length; index++) {
          if (value[index].id == e) {
            this.$set(this, 'province', value[index])
            this.unitChange()
          }
        }
      }
      this.form.dataUnitText = this.province.unitCode
    },
    unitChange() {
      if (this.province && this.province.unitCode && this.selectedRows && this.selectedRows.denominatorUnit) {
        if (this.province.unitCode == this.selectedRows.denominatorUnit) {
          this.$set(this.form, 'ratio', 1)
        } else {
          getAction("/emission/factor/cyEmissionFactor/api/getConvertValue", {
            sourceUnit: this.province.unitCode,
            targetUnit: this.selectedRows.denominatorUnit
          }).then((res) => {
            if (res.success) {
              this.$set(this.form, 'ratio', res.result)
              console.log('unitChange', this.form);
            }
          })
        }
      }
    },
    //关闭
    onClose() {
      this.$emit("onCloseBasicDrawerVisible", false);
    },
  },
};
</script>
<style lang="less" scoped>
.drawerOptionBox {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}

.manualOperation {
  background: #ffffff;
  border-radius: 3px 3px 3px 3px;
  font-weight: 400;
  font-size: 12px;
  color: #148958;
  line-height: 0;
  border: 1px solid #148958;
  padding: 4px 8px;
  display: flex;
  align-items: center;

  img {
    width: 14px;
    height: 14px;
    margin-right: 8px;
  }
}

.manual {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
}

.color1 {
  color: #888888;
}

.inpts {
  width: 80px !important;
}

.tianjia {
  width: 380px;
  height: 156px;
  background: #f8f8f8;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #d9d9d9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .color {
    color: #888888;
  }

  .leftShoudong {
    background: #fff !important;
    border-color: #148958 !important;
    color: #148958 !important;
  }

  .marRight {
    margin-left: 16px;
  }
}

.tables {
  padding: 24px;
  background: #ffffff;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #eeeeee;
  margin-top: 24px;
}

.top {
  background: #ffffff;
  border-radius: 3px 3px 3px 3px;
  padding: 24px 24px 0;
}

.marbton {
  margin-bottom: 24px;
}

.leftChaxun {
  background: #148958 !important;
  color: #fff !important;
}

//.ant-btn:hover {
//  border-color: #148958 !important;
//  color: #148958 !important;
//}

.leftChaxun:hover {
  background: #148958 !important;
  color: #fff !important;
}
.standard {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-bottom: 24px;
  .standard-select {
    width: 45%;
  }
  img {
    height: 100%;
    //上下居中
    margin-top: 30px;
  }
}
</style>
